package com.eshop.modules.mp.service;

import java.lang.invoke.SerializedLambda;
import com.eshop.modules.user.service.dto.WechatUserDto;
import java.io.Serializable;
import com.eshop.modules.user.domain.ShopUser;
import com.eshop.enums.ShopCommonEnum;
import com.eshop.api.EshopException;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.eshop.modules.mp.domain.WechatTemplate;
import cn.binarywang.wx.miniapp.api.WxMaService;
import me.chanjar.weixin.common.error.WxErrorException;
import com.eshop.modules.mp.config.WxMaConfiguration;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Map;
import com.eshop.modules.mp.enums.WechatTempateEnum;
import java.util.HashMap;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.eshop.modules.user.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class WeiXinSubscribeService
{
    @Autowired
    private UserService userService;
    @Autowired
    private WechatTemplateService wechatTemplateService;
    
    public void rechargeSuccessNotice(final String time, final String price, final Long uid) {
        final String openid = this.getUserOpenid(uid);
        if (StrUtil.isBlank((CharSequence)openid)) {
            return;
        }
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", "您的账户金币发生变动，详情如下：");
        map.put("keyword1", "充值");
        map.put("keyword2", time);
        map.put("keyword3", price);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.RECHARGE_SUCCESS.getValue());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            this.sendSubscribeMsg(openid, tempId, "/user/account", map);
        }
    }
    
    public void paySuccessNotice(final String orderId, final String price, final Long uid) {
        final String openid = this.getUserOpenid(uid);
        if (StrUtil.isBlank((CharSequence)openid)) {
            return;
        }
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        final Map<String, String> map = new HashMap<String, String>();
        map.put("amount1", price);
        map.put("date2", simpleDateFormat.format(new Date()));
        map.put("character_string3", orderId);
        map.put("time4", simpleDateFormat.format(new Date()));
        map.put("thing5", "yshop购买商品");
        final String tempId = this.getTempId(WechatTempateEnum.PAY_SUCCESS.getValue());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            this.sendSubscribeMsg(openid, tempId, "/order/detail/" + orderId, map);
        }
    }
    
    public void refundSuccessNotice(final String orderId, final String price, final Long uid, final String time) {
        final String openid = this.getUserOpenid(uid);
        if (StrUtil.isBlank((CharSequence)openid)) {
            return;
        }
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", "您的订单退款申请被通过，钱款将很快还至您的支付账户。");
        map.put("keyword1", orderId);
        map.put("keyword2", price);
        map.put("keyword3", time);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.REFUND_SUCCESS.getValue());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            this.sendSubscribeMsg(openid, tempId, "/order/detail/" + orderId, map);
        }
    }
    
    public void deliverySuccessNotice(final String orderId, final String deliveryName, final String deliveryId, final Long uid) {
        final String openid = this.getUserOpenid(uid);
        if (StrUtil.isEmpty((CharSequence)openid)) {
            return;
        }
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", "亲，宝贝已经启程了，好想快点来到你身边。");
        map.put("keyword2", deliveryName);
        map.put("keyword1", orderId);
        map.put("keyword3", deliveryId);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.DELIVERY_SUCCESS.getValue());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            this.sendSubscribeMsg(openid, tempId, "/order/detail/" + orderId, map);
        }
    }
    
    private void sendSubscribeMsg(final String openId, final String templateId, final String page, final Map<String, String> map) {
        final WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder().toUser(openId).templateId(templateId).page(page).build();
        map.forEach((k, v) -> wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.MsgData(k, v)));
        final WxMaService wxMaService = WxMaConfiguration.getWxMaService();
        try {
            wxMaService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
        }
        catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
    
    private String getTempId(final String key) {
        final WechatTemplate wechatTemplate = (WechatTemplate)((this.wechatTemplateService.lambdaQuery().eq(WechatTemplate::getType, "subscribe")).eq(WechatTemplate::getTempkey, key)).one();
        if (wechatTemplate == null) {
            throw new EshopException("请后台配置key:" + key + "订阅消息id");
        }
        if (ShopCommonEnum.IS_STATUS_0.getValue().equals(wechatTemplate.getStatus())) {
            return "";
        }
        return wechatTemplate.getTempid();
    }
    
    private String getUserOpenid(final Long uid) {
        final ShopUser shopUser = (ShopUser)this.userService.getById((Serializable)uid);
        if (shopUser == null) {
            return "";
        }
        final WechatUserDto wechatUserDto = shopUser.getWxProfile();
        if (wechatUserDto == null) {
            return "";
        }
        if (StrUtil.isBlank((CharSequence)wechatUserDto.getRoutineOpenid())) {
            return "";
        }
        return wechatUserDto.getRoutineOpenid();
    }
}
